package com.ww.myblog.web.admin;

import com.ww.myblog.po.User;
import com.ww.myblog.service.UserService;
import com.ww.myblog.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    private UserService userService;

    @GetMapping
    public String loginPage(){
        return "admin/login";
    }

    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password, HttpSession session, RedirectAttributes attributes){
        // 登录功能实现
        User user = userService.checkUser(username, password);
        if(user != null){
            // 用户名密码正确，返回后台index页面
            // 将密码置为空，防止把密码返回到前端页面
            user.setPassword(null);
            session.setAttribute("user",user);
            return "/admin/index";
        }else{
            attributes.addFlashAttribute("message","用户名或密码错误");
            return "redirect:/admin";
        }

    }

    @GetMapping("logout")
    public String logout(HttpSession session){
        // 注销，将session中的user清空
        session.removeAttribute("user");
        return "redirect:/admin";
    }

}
